#include <Arduino.h>
#include "Modbus_RTU.h"
#include "DepthSensor.h"
#include "CODSensor.h"
#include "DOSensor.h"
#include "MQTTFunc.h"
#include "BDS.hpp"
#define BaudRate 115200 //与客户端的通信波特率
#define DS18B20_Pin 13 //温度传感器数据线
#define WIFIMode_ChangePin 12 //wifi模式选择

DepthSensor ds;
CODSensor cods;
Modbus_RTU modbus;
DOSensor dos;
MQTTFunc mqtt;
BDS bds;

String format5char(short data)
{
  char chs[6]; // 5个字节
  int width = 5;//宽度为5
  sprintf(chs,"%*d",width,data);
  return String(chs);
}

String float_format10char(float data)
{
  char chs[11]; // 5个字节
  int width = 10;//宽度为10
  sprintf(chs,"%*.6f",width,data);
  return String(chs);
}

String get_DepthVal(SensorData & dataStruct)
{
  int depth = ds.ReadDepth();
  dataStruct.Depth = depth;
  Serial.print("Depth is:  ");
  Serial.print(depth);
  Serial.println(" cm");
  String str = "Depth=" + format5char(depth);
  return str;
}

String get_CODVal(SensorData & dataStruct)
{
  float COD_Val = cods.ReadCOD();
  float COD_Temp = cods.ReadTemperature();
  float COD_PH = cods.ReadPH();
  dataStruct.COD_Val = short(COD_Val*100);
  dataStruct.COD_Temp = short(COD_Temp*100);
  dataStruct.COD_PH = short(COD_PH*100);
  Serial.print("COD Value is:  ");
  Serial.print(COD_Val);
  Serial.print(" mg/L");

  Serial.print(" ,Temperature Value form COD Sensor is:  ");
  Serial.print(COD_Temp);
  Serial.print(" ℃");

  Serial.print(" ,PH Value from COD Sensor is:  ");
  Serial.println(COD_PH);

  String str = "COD_Val=" + format5char((int)(COD_Val*100)) + ",COD_Temp=" + format5char((int)(COD_Temp*100)) + ",COD_PH=" + format5char((int)(COD_PH*100));
  return str;
}

String get_DOVal(SensorData & dataStruct)
{
  dos.ReadDO_PH_Temp_Data();
  float DO_Val = dos.GetDOValue();
  float DO_Perc = dos.GetDOPercent();
  float DO_Temp = dos.GetTemperature();
  float DO_PH = dos.GetPH();
  dataStruct.DO_Val = short(DO_Val*100);
  dataStruct.DO_Perc = short(DO_Perc*100);
  dataStruct.DO_Temp = short(DO_Temp*100);
  dataStruct.DO_PH = short(DO_PH*100);
  Serial.print("DO Value is:  ");
  Serial.print(DO_Val);
  Serial.print(" mg/L");
  
  Serial.print(" ,DO in percent is:  ");
  Serial.print(DO_Perc);
  Serial.print(" %");

  Serial.print(" ,Temperature Value form DO Sensor is:  ");
  Serial.print(DO_Temp);
  Serial.print(" ℃");

  Serial.print(" ,PH Value from DO Sensor is:  ");
  Serial.println(DO_PH);

  String str = "DO_Val=" + format5char((int)(DO_Val*100)) + ",DO_Perc=" + format5char((int)(DO_Perc*100)) + ",DO_Temp=" + format5char((int)(DO_Temp*100)) + ",DO_PH=" + format5char((int)(DO_PH*100));
  return str;
}

String get_Loc(SensorData & dataStruct)
{
  FixedPoint fixed_point = bds.GetFixedPoint();
  dataStruct.lati = fixed_point.latitude;
  dataStruct.longi = fixed_point.longitude;
  dataStruct.time_str = fixed_point.time_str;
  Serial.print("The BDS recved longitude = ");
  Serial.print(fixed_point.longitude, 6);
  Serial.print(", latitude = ");
  Serial.print(fixed_point.latitude, 6);
  Serial.print(", time = ");
  Serial.println(fixed_point.time_str);
  String str = "Longi=" + float_format10char(fixed_point.longitude) + ",Lati=" +  float_format10char(fixed_point.latitude) + ",time=" + fixed_point.time_str;
  return str;
}

String PackData(SensorData & dataStruct)
{
  String data = get_DepthVal(dataStruct) + "," + get_CODVal(dataStruct) + "," + get_DOVal(dataStruct) + "," + get_Loc(dataStruct);
  // Serial.println(data);
  return data;
}

void SendString(void)
{
  SensorData data;
  mqtt.SendString(PackData(data));// 原本的字符串编码
  // PackData(data);
  // mqtt.SendString(mqtt.DecodeSensorData2JsonString(data));
}

void callback(char *topic, byte *payload, unsigned int length)
{
// //  Serial.println("message rev:");
// //  Serial.println(topic);
//   for (size_t i = 0; i < length; i++)
//   {
//     Serial.print((char)payload[i]);
//   }
//   Serial.println();
//    if ((char)payload[0] == 'b') {
//      digitalWrite(RELAY_PIN, HIGH); // 将继电器引脚设置为高电平，触发继电器动作
//  delay(1000); // 等待1秒钟
//     }
//   else if
// ((char)payload[0] == 'a') {
//       digitalWrite(RELAY_PIN, LOW); // 将继电器引脚设置为高电平，触发继电器动作
//   delay(1000); // 等待1秒钟
//     }
//   if (strstr(topic, ONENET_TOPIC_PROP_SET))
//   {
//     DynamicJsonDocument doc(100);
//     DeserializationError error = deserializeJson(doc, payload);
//     if (error)
//     {
//       Serial.println("parse json failed");
//       return;
//     }
//     JsonObject setAlinkMsgObj = doc.as<JsonObject>();
//     serializeJsonPretty(setAlinkMsgObj, Serial);
//     String str = setAlinkMsgObj["id"];
//     Serial.println(str);
//     char sendbuf[100];
//     sprintf(sendbuf, "{\"id\": \"%s\",\"code\":200,\"msg\":\"success\"}", str.c_str());
//     Serial.println(sendbuf);
//     client->publish(ONENET_TOPIC_PROP_SET_REPLY, sendbuf);
//   }
//   if (strstr(topic, ONENET_TOPIC_PROP_GET))
//   {
//     DynamicJsonDocument doc(100);
//     DeserializationError error = deserializeJson(doc, payload);
//     if (error)
//     {
//       Serial.println("parse json failed");
//       return;
//     }
//     JsonObject setAlinkMsgObj = doc.as<JsonObject>();
//     serializeJsonPretty(setAlinkMsgObj, Serial);
//     String str = setAlinkMsgObj["id"];
//     Serial.println(str);
//     char sendbuf[100];
// -
//     sprintf(sendbuf, "{\"id\": \"%s\",\"code\":200,\"msg\":\"success\",\"data\":{\"dis\":%.2f }}", str.c_str(), temp);
//     Serial.println(sendbuf);
//     client->publish(ONENET_TOPIC_PROP_GET_REPLY, sendbuf);
//   }
}
void setup(void)
{
  Serial.begin(BaudRate);
  Serial.println("System begin!");
  bds.init_BDS(BDS::BaudRate_115200);
  modbus.initTrans(Modbus_RTU::BaudRate_9600); // modbus 初始化
  ds.initFunc(&modbus);
  cods.initCODSensor(&modbus);
  dos.initDOSensor(&modbus);
  mqtt.init(callback,SendString);
  
}
  
void loop(void)
{
  // PackData();
  bds.check_Data();
  mqtt.checkWIFI();
  mqtt.checkConnect();
}
